import type { Directive } from 'vue'

// 节流指令
export const throttle: Directive = {
  mounted(el, binding) {
    const { value, arg } = binding
    const delay = arg ? parseInt(arg) : 300
    
    let lastTime = 0
    
    el._throttleHandler = (event: Event) => {
      const now = Date.now()
      
      if (now - lastTime >= delay) {
        lastTime = now
        if (typeof value === 'function') {
          value(event)
        }
      }
    }
    
    el.addEventListener('click', el._throttleHandler)
  },
  
  unmounted(el) {
    if (el._throttleHandler) {
      el.removeEventListener('click', el._throttleHandler)
      delete el._throttleHandler
    }
  }
}
